/**
 * Copyright (c) 2016, smuyyh@gmail.com All Rights Reserved.
 * #                                                   #
 * #                       _oo0oo_                     #
 * #                      o8888888o                    #
 * #                      88" . "88                    #
 * #                      (| -_- |)                    #
 * #                      0\  =  /0                    #
 * #                    ___/`---'\___                  #
 * #                  .' \\|     |# '.                 #
 * #                 / \\|||  :  |||# \                #
 * #                / _||||| -:- |||||- \              #
 * #               |   | \\\  -  #/ |   |              #
 * #               | \_|  ''\---/''  |_/ |             #
 * #               \  .-\__  '-'  ___/-. /             #
 * #             ___'. .'  /--.--\  `. .'___           #
 * #          ."" '<  `.___\_<|>_/___.' >' "".         #
 * #         | | :  `- \`.;`\ _ /`;.`/ - ` : | |       #
 * #         \  \ `_.   \_ __\ /__ _/   .-` /  /       #
 * #     =====`-.____`.___ \_____/___.-`___.-'=====    #
 * #                       `=---='                     #
 * #     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   #
 * #                                                   #
 * #               佛祖保佑         永无BUG             #
 * #                                                   #
 */
package com.ecy.quadratic.ui.fragment;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.widget.ImageView;

import com.ecy.quadratic.R;
import com.ecy.quadratic.manager.EventManager;
import com.ecy.quadratic.reader.base.BaseFragment;
import com.ecy.quadratic.reader.base.Constant;
import com.ecy.quadratic.reader.bean.user.TencentLoginResult;
import com.ecy.quadratic.reader.component.AppComponent;
import com.ecy.quadratic.reader.component.DaggerMainComponent;
import com.ecy.quadratic.reader.service.DownloadBookService;
import com.ecy.quadratic.reader.ui.contract.MainContract;
import com.ecy.quadratic.reader.ui.fragment.SubCategoryFragment;
import com.ecy.quadratic.reader.ui.presenter.MainActivityPresenter;
import com.ecy.quadratic.reader.utils.LogUtils;
import com.ecy.quadratic.reader.utils.ToastUtils;
import com.ecy.quadratic.reader.view.GenderPopupWindow;
import com.ecy.quadratic.reader.view.LoginPopupWindow;
import com.ecy.quadratic.widget.PagerSlidingTabStrip;
import com.google.gson.Gson;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;

import butterknife.Bind;

/**
 * https://github.com/JustWayward/BookReader
 */
public class NovelRoomFragmnt extends BaseFragment implements MainContract.View, LoginPopupWindow.LoginTypeListener {

    // 退出间隔
    private static final int BACK_PRESSED_INTERVAL = 2000;
    public static Tencent mTencent;
    public IUiListener loginListener;
    @Bind(R.id.tabs)
    PagerSlidingTabStrip mIndicator;
    @Bind(R.id.tab_viewpager)
    ViewPager mViewPager;
    @Inject
    MainActivityPresenter mPresenter;
    private List<Fragment> mTabContents;
    private FragmentPagerAdapter mAdapter;
    private List<String> mDatas;
    // 退出时间
    private long currentBackPressedTime = 0;
    private LoginPopupWindow popupWindow;
    private GenderPopupWindow genderPopupWindow;

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_novel_main;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMainComponent.builder()
                .appComponent(appComponent)
                .build()
                .inject(this);
    }

    @Override
    public void attachView() {

    }

    @Override
    public void initData() {
        getContext().startService(new Intent(getContext(), DownloadBookService.class));

//        mTencent = Tencent.createInstance("1105670298", BookMainFragmnt1.this);

        mDatas = Arrays.asList(getResources().getStringArray(R.array.home_tabs));
        mTabContents = new ArrayList<>();
        int dataSize = mDatas.size();
//        mTabContents.add(new BookRecommendFragment0());
//        mTabContents.add(new BookRecommendFragment0());
        for (int i = 0; i < dataSize; i++) {
            mTabContents.add(SubCategoryFragment.newInstance(mDatas.get(i), "", Constant.Gender.MALE, Constant.CateType.HOT));
        }


        mAdapter = new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public int getCount() {
                return mTabContents.size();
            }

            @Override
            public Fragment getItem(int position) {
                return mTabContents.get(position);
            }
        };
    }

    @Override
    public void configViews() {
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mTabContents.get(position);
            }

            @Override
            public int getCount() {
                return mDatas.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {  //注释掉，因为tablayout导航卡名字是根据这里进行绑定的，现在我们自定义了，不需要了
                return mDatas.get(position);
            }

        });
        mIndicator.setOnTabReselectedListener(new PagerSlidingTabStrip.OnTabReselectedListener() {
            @Override
            public void onTabReselected(int position) {
                mViewPager.setCurrentItem(position);
            }
        });
        final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
                .getDisplayMetrics());
        mViewPager.setPageMargin(pageMargin);
        mViewPager.setCurrentItem(0);
        mIndicator.setViewPager(mViewPager);

        mPresenter.attachView(this);

        mIndicator.postDelayed(new Runnable() {
            @Override
            public void run() {
                showChooseSexPopupWindow();
            }
        }, 500);
    }

    public void showChooseSexPopupWindow() {
        if (genderPopupWindow == null) {
            genderPopupWindow = new GenderPopupWindow(getActivity());
        }
//        if (!SettingManager.getInstance().isUserChooseSex()
//                && !genderPopupWindow.isShowing()) {
//            genderPopupWindow.showAtLocation(mIndicator, Gravity.CENTER, 0, 0);
//        }
    }

    public void setCurrentItem(int position) {
        mViewPager.setCurrentItem(position);
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_main, menu);
//        return true;
//    }


   /* @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.action_search:
                startActivity(new Intent(BookMainFragmnt1.this, SearchActivity.class));
                break;
            case R.id.action_login:
                if (popupWindow == null) {
                    popupWindow = new LoginPopupWindow(this);
                    popupWindow.setLoginTypeListener(this);
                }
                popupWindow.showAtLocation(mCommonToolbar, Gravity.CENTER, 0, 0);
                break;
            case R.id.action_my_message:
                if (popupWindow == null) {
                    popupWindow = new LoginPopupWindow(this);
                    popupWindow.setLoginTypeListener(this);
                }
                popupWindow.showAtLocation(mCommonToolbar, Gravity.CENTER, 0, 0);
                break;
            case R.id.action_sync_bookshelf:
                showDialog();
                mPresenter.syncBookShelf();
               *//* if (popupWindow == null) {
                    popupWindow = new LoginPopupWindow(this);
                    popupWindow.setLoginTypeListener(this);
                }
                popupWindow.showAtLocation(mCommonToolbar, Gravity.CENTER, 0, 0);*//*
                break;
            case R.id.action_scan_local_book:
                ScanLocalBookActivity.startActivity(this);
                break;
            case R.id.action_wifi_book:
                WifiBookActivity.startActivity(this);
                break;
            case R.id.action_feedback:
                FeedbackActivity.startActivity(this);
                break;
            case R.id.action_night_mode:
                if (SharedPreferencesUtil.getInstance().getBoolean(Constant.ISNIGHT, false)) {
                    SharedPreferencesUtil.getInstance().putBoolean(Constant.ISNIGHT, false);
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                } else {
                    SharedPreferencesUtil.getInstance().putBoolean(Constant.ISNIGHT, true);
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                }
                recreate();
                break;
            case R.id.action_settings:
                SettingActivity.startActivity(this);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }*/

//    @Override
//    public boolean dispatchKeyEvent(KeyEvent event) {
//        if (event.getAction() == KeyEvent.ACTION_DOWN
//                && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
//            if (System.currentTimeMillis() - currentBackPressedTime > BACK_PRESSED_INTERVAL) {
//                currentBackPressedTime = System.currentTimeMillis();
//                ToastUtils.showToast(getString(R.string.exit_tips));
//                return true;
//            } else {
//                finish(); // 退出
//            }
//        } else if (event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
//            return true;
//        }
//        return super.dispatchKeyEvent(event);
//    }

//    /**
//     * 显示item中的图片；
//     *
//     * @param view
//     * @param menu
//     * @return
//     */
//    @Override
//    protected boolean onPrepareOptionsPanel(View view, Menu menu) {
//        if (menu != null) {
//            if (menu.getClass() == MenuBuilder.class) {
//                try {
//                    Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
//                    m.setAccessible(true);
//                    m.invoke(menu, true);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return super.onPrepareOptionsPanel(view, menu);
//    }

    @Override
    public void loginSuccess() {
        ToastUtils.showSingleToast("登陆成功");
    }

    @Override
    public void syncBookShelfCompleted() {
        dismissDialog();
        EventManager.refreshCollectionList();
    }

    @Override
    public void onLogin(ImageView view, String type) {
        if (type.equals("QQ")) {
            if (!mTencent.isSessionValid()) {
                if (loginListener == null) loginListener = new BaseUIListener();
                mTencent.login(this, "all", loginListener);
            }
        }
        //4f45e920ff5d1a0e29d997986cd97181
    }

    @Override
    public void showError() {
        ToastUtils.showSingleToast("同步异常");
        dismissDialog();
    }

    @Override
    public void complete() {

    }


    public class BaseUIListener implements IUiListener {

        @Override
        public void onComplete(Object o) {
            JSONObject jsonObject = (JSONObject) o;
            String json = jsonObject.toString();
            Gson gson = new Gson();
            TencentLoginResult result = gson.fromJson(json, TencentLoginResult.class);
            LogUtils.e(result.toString());
            mPresenter.login(result.openid, result.access_token, "QQ");
        }

        @Override
        public void onError(UiError uiError) {
        }

        @Override
        public void onCancel() {

        }
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (requestCode == Constants.REQUEST_LOGIN || requestCode == Constants.REQUEST_APPBAR) {
//            Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
//        }
//        super.onActivityResult(requestCode, resultCode, data);
//    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        DownloadBookService.cancel();
//        stopService(new Intent(this, DownloadBookService.class));
//        if (mPresenter != null) {
//            mPresenter.detachView();
//        }
//    }
}